package com.neuronbit.businessflow.intellij.editor.codec;

import com.mxgraph.io.mxObjectCodec;
import com.neuronbit.businessflow.intellij.model.FormattedMethodString;
import com.neuronbit.businessflow.intellij.model.SimpleType;
import com.neuronbit.businessflow.intellij.model.ExceptionHandler;
import com.neuronbit.businessflow.intellij.model.Type;

/**
 * The type exception handler codec.
 */
public class ExceptionHandlerCodec extends mxObjectCodec {
    /**
     * Instantiates a new exception handler codec.
     */
    public ExceptionHandlerCodec() {
        super(new ExceptionHandler());
    }

    @Override
    protected Object getFieldValue(Object obj, String fieldName) {
        Object fieldValue = super.getFieldValue(obj, fieldName);
        if (fieldName.equals("type") && fieldValue != null) {
            return ((Type) fieldValue).getQualifiedName();
        }
        if (fieldName.equals("method") && fieldValue != null) {
            return ((FormattedMethodString) fieldValue).getValue();
        }
        return fieldValue;
    }

    @Override
    protected void setFieldValue(Object obj, String fieldName, Object value) {
        if (fieldName.equals("type") && value != null) {
            super.setFieldValue(obj, fieldName, SimpleType.of(value.toString()));
        } else if (fieldName.equals("method") && value != null) {
            super.setFieldValue(obj, fieldName, new FormattedMethodString(value.toString()));
        } else {
            super.setFieldValue(obj, fieldName, value);
        }
    }
}
